from sqlalchemy.sql.elements import and_

from SQLConfig import db
import datetime


class Patient(db.Model):
    """
    患者数据表
    """
    __tablename__ = "patients"
    id = db.Column(db.Integer, primary_key=True, index=True)  # 主键，病人编号
    name = db.Column(db.String(20))  # 姓名
    gender = db.Column(db.String(5))  # 性别
    age = db.Column(db.String(5))  # 年龄
    time = db.Column(db.String(10))  # 挂号时间，默认为当前
    phone = db.Column(db.String(20))  # 手机号码
    username = db.Column(db.String(20))  # 所属医生

    def __init__(self, name, gender, age, time, phone, username):
        self.name = name
        self.gender = gender
        self.age = age
        self.time = time
        self.phone = phone
        self.username = username


class PatientSQLOperation:
    """
    操作患者数据表的类
    """

    @staticmethod
    def insert(name, gender, age, time, phone, username):
        if PatientSQLOperation.search(name) is None:
            patient=Patient(name, gender, age, time, phone, username)
            db.session.add(patient)
            db.session.flush()
            db.session.commit()
            return patient.id
        else:
            return 0

    @staticmethod
    def deleteByid(patientId):
        if not PatientSQLOperation.searchById(patientId):
            return "patient not exist"
        Patient.query.filter(Patient.id == patientId).delete()
        db.session.commit()
        return "OK"

    @staticmethod
    def search(name="", phone=""):
        if name == "":
            return Patient.query.filter(Patient.phone == phone).first()
        elif phone == "":
            return Patient.query.filter(Patient.name == name).first()
        else:
            return Patient.query.filter(Patient.phone == phone, Patient.phone == phone).first()

    @staticmethod
    def updateById(patientId, name="", gender="", age="", time="", phone=""):
        if name != "":
            Patient.query.filter(Patient.id == patientId).update({'name': name})
        if gender != "":
            Patient.query.filter(Patient.id == patientId).update({'gender': gender})
        if age != "":
            Patient.query.filter(Patient.id == patientId).update({'age': age})
        if time != "":
            Patient.query.filter(Patient.id == patientId).update({'time': time})
        if gender != "":
            Patient.query.filter(Patient.id == patientId).update({'gender': gender})
        if phone != "":
            Patient.query.filter(Patient.id == patientId).update({'phone': phone})
        db.session.commit()

    @staticmethod
    def searchById(patientId):
        """
        存在此id的病人则返回 True，不存在则返回 False
        """
        return Patient.query.filter(Patient.id == patientId).first() is not None

    @staticmethod
    def getAllPatients(username):
        return Patient.query.filter(Patient.username == username)



if __name__ == "__main__":
    db.create_all()
